/*
 * Copyright (C) 2009 Rafael Fernandes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonebooksharing.android.async;

import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ListView;

import com.phonebooksharing.android.util.Global;
import com.phonebooksharing.android.util.GalleryUtilities;
import com.phonebooksharing.android.util.NetworkHandlerTask;

public class LoadNetworkImageTask extends NetworkHandlerTask<Object, Object, Void> {
    private ListView lv;
    private String defaultUrl;
    private boolean isExternal;
    public String externalID;
    
    public LoadNetworkImageTask(ListView lv) {
        this(lv, null, false);
    }

    public LoadNetworkImageTask(ListView lv, String url, boolean isExternal) {
        this.lv = lv;
        this.defaultUrl = url;
        this.isExternal = isExternal;
    }

    @Override
    public Void doInBackground(Object... params) {
        try {
            long id = (Long)params[0];
            int  w  = (Integer)params[1];
            int  h  = (Integer)params[2];
            boolean isThumbnail = false;
            int rIdIcon = 0;
            if(params.length > 5) {
                isThumbnail = (Boolean)params[4];
                rIdIcon = (Integer)params[5];
            }
            
            String url;
            if(!TextUtils.isEmpty(defaultUrl)) {
                url = defaultUrl;
            } else {
                url = String.format("http:" + Global.IMAGE_SERVLET_URL, "g" /*ac*/, id /*q*/, "" /*c*/, "" /*p*/, "" /*ps*/, "" /*mt*/, w /*w*/, h /*h*/);
            }
            
            Bitmap b = GalleryUtilities.load(url, isExternal);
            final Bitmap bm = GalleryUtilities.scaleAndFrame(b, w, h);
    
            b.recycle();
            b = null;
            
            publishProgress(params[0], bm, params[3], isThumbnail, rIdIcon);
        } catch(Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    @Override
    public void onProgressUpdate(Object... result) {
        super.onProgressUpdate(result);
        try {
            //common params
            final Long id = (Long)result[0];
            final Bitmap bitmap = (Bitmap)result[1];
            final View view;
            int rIdIcon = (Integer)result[4];
    
            // skip if bitmap wasnt found
            if(bitmap == null) return;
    
            if(!isExternal) {
                GalleryUtilities.addToImageCache(id, bitmap);
            } else {
                GalleryUtilities.addToWishlistThumbCache(externalID, bitmap);
            }
    
            final int lvPosition, groupPosition, childPosition;
            //normal listview
            if(lv instanceof ExpandableListView) {
    
                groupPosition = (Integer)result[2];
                childPosition = (Integer)result[3];
                
                final long packetPos = ExpandableListView.getPackedPositionForChild(groupPosition, childPosition);
                final ExpandableListView elv = (ExpandableListView)lv;
                
                //skip updating this item if outside of bounds
                if(elv.getFlatListPosition(packetPos) <  lv.getFirstVisiblePosition() || elv.getFlatListPosition(packetPos) > lv.getLastVisiblePosition()) return;
                
                // find actual position and update view
                int visible = elv.getFlatListPosition(packetPos) - lv.getFirstVisiblePosition();
                view = lv.getChildAt(visible + 2);//add 2 (list view header and group header)
                
            } else {
                lvPosition = (Integer)result[2];
              //skip updating this item if outside of bounds
                if(lvPosition < lv.getFirstVisiblePosition() || lvPosition > lv.getLastVisiblePosition()) return;
                
                // find actual position and update view
                int visible = lvPosition - lv.getFirstVisiblePosition();
                view = lv.getChildAt(visible);
            }
            
            final ImageView iv;
            if(rIdIcon > 0) {
                iv = (ImageView)view.findViewById(rIdIcon);
            } else {
                iv = (ImageView)view.findViewById(android.R.id.icon);
            }
            
            iv.removeCallbacks(null);
            iv.setImageBitmap(null);
            iv.setImageBitmap(bitmap);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}